<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .a {
            width: 50px;
            height: 50px;
            background-color: #f00;
            position: absolute;
            border: 10px solid #000;
        }
    </style>
</head>

<body>
    <div class="a"></div>

    <script>


        // e.clientX   e.clientY   鼠标的坐标
        // clientWidth / clientHeight  盒子里面的宽高
        // offsetWidth / offsetHeight  盒子加上边框的宽高




        var oA = document.querySelector('.a');

        var r = oA.offsetWidth / 2;

        var maxX = document.documentElement.clientWidth - oA.offsetWidth;
        var maxY = document.documentElement.clientHeight - oA.offsetHeight;

        document.onmousemove = function (e) {
            var x = e.clientX - r;
            var y = e.clientY - r;
            if (x < 0) x = 0;
            if (y < 0) y = 0;
            if (x > maxX) x = maxX;
            if (y > maxY) y = maxY;
            oA.style.left = x + 'px';
            oA.style.top = y + 'px';
        }

    </script>

</body>

</html>